﻿using System;
using System.Configuration;
using GC_VKMD.MusicDownloaderClient.Abstractions.Helpers;

namespace GC_VKMD.MusicDownloaderClient.Helpers
{
	public class ApplicationConfiguration : BaseApplicationConfiguration
	{
		#region Variables

		private Configuration _manager;
		private readonly string _configurationFileName;
		private readonly object _syncObj = new object();

		#endregion

		#region Constructors

		public ApplicationConfiguration(string configurationFileName)
		{
			_configurationFileName = configurationFileName;
			if (string.IsNullOrWhiteSpace(_configurationFileName))
				throw new ArgumentNullException(string.Format("Path to configuration file doesn't valid"));
		}

		#endregion

		#region Base Class Members

		public override string Get(string name)
		{
			lock (_syncObj)
			{
				return Manager.AppSettings.Settings[name].Value;
			}
		}

		public override void Set(string name, string value)
		{
			lock (_syncObj)
			{
				Manager.AppSettings.Settings[name].Value = value;
				Save();
			}
		}

		public override void ReopenConfigFile()
		{
			_manager = null;
		}

		#endregion

		#region Internal Implementation

		private void Save()
		{
			try
			{
				Manager.Save(ConfigurationSaveMode.Minimal);
			}
			catch (ConfigurationErrorsException exception)
			{
				ApplicationLogger.Logger.LoggingExceptionMessage(exception);
				_manager = null;
			}
		}

		private Configuration Manager
		{
			get { return _manager ?? (_manager = ConfigurationManager.OpenExeConfiguration(_configurationFileName)); }
		}

		#endregion
	}
}
